package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.vos.ApCommentRepayVo;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //检查参数
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //按文章id过滤，设置分页和排序
        Query query = Query.query(Criteria.where("commentId")
                .is(dto.getCommentId())
                .and("createdTime")
                .lt(dto.getMinDate()));
        query.limit(dto.getSize()).with(Sort
                .by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //返回封装数据
        //判断用户是否登录
        //用户未登录直接返回数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(list);
        }
        //用户已登录，加载数据，需要判断当前用户点赞了哪些评论
        List<String> idList = list.stream()
                .map(x -> x.getId())
                .collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId")
                .in(idList).and("authorId")
                .is(user.getId()));

        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);

        ArrayList<ApCommentRepayVo> resultList = new ArrayList<>();
        if (list != null && apCommentRepayLikes != null) {
            list.stream().forEach(x -> {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(x, apCommentRepayVo);
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if (x.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                        apCommentRepayVo.setOperation((short) 0);
                    }
                }
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        } else {
            return ResponseResult.okResult(list);
        }
    }

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if (dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getCommentId()!=null&&dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"评论不能超过140字 ");
        }
        //判断是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请登录后再评论 ");
        }
        //保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);

        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //检查参数
        if (dto.getCommentRepayId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"评论不存在");
        }
       //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //点赞
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay!=null&&dto.getOperation()==0){
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            //计算热点评论

            //保存 APP评论信息点赞
            ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentRepayId(apCommentRepay.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        }else if (apCommentRepay!=null&&dto.getOperation()==1){
            //取消点赞
            //更新评论点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
            //更新app评论信息点赞
            mongoTemplate.remove(Query.query(Criteria.where("authorId")
                    .is(user.getId())
                    .and("commentRepayId").is(apCommentRepay.getId())),ApCommentRepayLike.class);
        }
        HashMap<String, Object> mapResult = new HashMap<>();
        mapResult.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(mapResult);
    }
}
